﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TheOutfield.UmbExt.UniversalMediaPicker.Xslt;
using TheOutfield.UmbExt.UniversalMediaPicker.Extensions;
using System.Xml.XPath;
using System.Xml;
using umbraco;

namespace TheOutfield.UmbExt.UniversalMediaPicker.Providers.Dropbox
{
    public class DropboxXsltExtension : AbstractXsltExtension
    {
        public static XPathNodeIterator GetMedia(int docTypeDefinitionId, string path)
        {
            var provider = GetProvider<DropboxProvider>(docTypeDefinitionId);
            var service = new DropboxService(provider.Config);

            try
            {
                var meta = service.GetMetaDataItem(path);

                var xd = new XmlDocument();
                var docNode = xmlHelper.addTextNode(xd, "File", "");

                if (meta != null)
                {
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Path", meta.Path));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Name", meta.Name));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Size", meta.Size));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Extension", meta.Extension));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Modified", meta.Modified.ToString("yyyy-MMM-dd")));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Url", string.Format("/dropbox.ashx?dtdid={0}&path={1}", docTypeDefinitionId, path)));
                }

                xd.AppendChild(docNode);

                return xd.CreateNavigator().Select("/File");
            }
            catch (Exception e)
            {
                return e.ToXPathNodeIterator();
            }
        }
    }
}